/**
 * <pre>
 * Title: 		PasswordController.java
 * Author:		linriqing
 * Create:	 	2010-8-17 下午02:52:21
 * Copyright: 	Copyright (c) 2010
 * Company:		Shenzhen Helper
 * <pre>
 */
package com.hengpeng.itfinoss.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.hengpeng.common.acl.vo.Passport;
import com.hengpeng.common.constant.Constant;
import com.hengpeng.common.persist.query.DynamicQuery;
import com.hengpeng.common.persist.query.Restrictions;
import com.hengpeng.common.util.MD5;
import com.hengpeng.itfinbase.persist.AppUser;
import com.hengpeng.itfinoss.controller.util.PageHandlerUtil;
import com.hengpeng.itfinoss.service.ServiceFactory;

/**
 * <pre>
 * 密码控制器
 * </pre>
 * @author linriqing
 * @version 1.0, 2010-8-17
 */
@Controller
@RequestMapping(value = "/password")
public class PasswordController extends BaseController
{
	@Autowired
	private ServiceFactory serviceFactory;

	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView entry()
	{
		return new ModelAndView("/common/password");
	}

	@RequestMapping(method = RequestMethod.POST)
	public String change(HttpServletRequest request, String oldPwd, String newPwd, ModelMap modelmap)
	{
		try
		{
			if (validateObjectsNullOrEmpty(oldPwd, newPwd))
			{
				return returnError(modelmap, " 数据未通过验证，请刷新重试！");
			}
			Passport passport = (Passport) request.getSession().getAttribute(Constant.PROFILE_SESSION_NAME);
			DynamicQuery query = new DynamicQuery(AppUser.class);
			query.add(Restrictions.eq("loginName", passport.getUserId()));
			query.add(Restrictions.eq("password", MD5.encodeString(oldPwd, "utf-8")));
			List<AppUser> findByNamedQuery = serviceFactory.getPersistService().find(AppUser.class, query);
			if (findByNamedQuery.size() > 0)
			{
				AppUser user = findByNamedQuery.get(0);
				user.setPassword(MD5.encodeString(newPwd, "utf-8"));
				serviceFactory.getPersistService().update(user);
			}
			else
			{
				return returnError(modelmap, " 您输入的旧密码错误！");
			}

			return returnSuccess(modelmap, "恭喜您，密码修改成功！", "");
		}
		catch (RuntimeException e)
		{
			return PageHandlerUtil.returnError(modelmap, e);
		}
	}
}
